package thread.lockpackage;

/**
 * 使用wait和notify
 */
public class PrintABCWithStatusSyn {

    private static final int count = 10;
    private static volatile int status = 0;
    private static final Object object = new Object();

    public static void main(String[] args) {

        try {
            Thread threadA = new Thread(new Printer(0, 1, "A"));
            Thread threadB = new Thread(new Printer(1, 2, "B"));
            Thread threadC = new Thread(new Printer(2, 3, "C"));
            threadA.start();
            Thread.sleep(100);
            threadB.start();
            Thread.sleep(100);
            threadC.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class Printer implements Runnable {

        private final int currentStatus;
        private final int nextStatus;
        private final String printerChar;

        public Printer(int currentStatus, int nextStatus, String printerChar) {
            super();
            this.currentStatus = currentStatus;
            this.nextStatus = nextStatus;
            this.printerChar = printerChar;
        }

        @Override
        public void run() {
            synchronized (object) {
                for (int i = 0; i < count; i++) {
                    while (status != currentStatus) {
                        // 当不是当前的标志时放弃锁
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            return;
                        }
                    }
                    System.out.println(printerChar);
                    status = nextStatus;
                    object.notifyAll();
                }
            }
        }
    }

}
